package org.loofer.ext.utils;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build.VERSION;
import android.util.DisplayMetrics;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewParent;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import org.loofer.ext.Ext;
import org.loofer.ext.component.logger.Logger;
import io.rong.common.ResourceUtils;

public final class ViewUtils {
    private static final boolean DEBUG = false;
    private static final Object TAG_DECORATE = new Object();
    private static float density;
    private static int screenHeight;
    private static int screenWidth;

    private static class DecorateContainer extends FrameLayout {
        private final View mHostView;

        public DecorateContainer(Context context, View hostView) {
            super(context);
            this.mHostView = hostView;
        }

        public int getVisibility() {
            return this.mHostView != null ? this.mHostView.getVisibility() : super.getVisibility();
        }
    }

    static {
        density = -1.0f;
        screenWidth = -1;
        screenHeight = -1;
        DisplayMetrics metris = Ext.getContext().getResources().getDisplayMetrics();
        density = metris.density;
        if (metris.widthPixels < metris.heightPixels) {
            screenWidth = metris.widthPixels;
            screenHeight = metris.heightPixels;
            return;
        }
        screenHeight = metris.widthPixels;
        screenWidth = metris.heightPixels;
        Logger.d("ViewUtils", "screenHeight:" + screenHeight + ",screenWidth:" + screenWidth);
    }

    private ViewUtils() {
    }

    public static <T extends View> T findById(View view, int id) {
        return view.findViewById(id);
    }

    public static void preventViewMultipleClick(final View v, int protectionMilliseconds) {
        v.setClickable(false);
        v.setEnabled(false);
        v.postDelayed(new Runnable() {
            public void run() {
                v.setClickable(true);
                v.setEnabled(true);
            }
        }, (long) protectionMilliseconds);
    }

    public static void setTag(View view, Object tag) {
        setTagInternal(view, 0, tag, true);
    }

    public static Object getTag(View view) {
        return getTagInternal(view, 0);
    }

    public static void setTag(View view, int key, Object tag) {
        setTagInternal(view, key, tag, false);
    }

    public static Object getTag(View view, int key) {
        return getTagInternal(view, key);
    }

    private static void setTagInternal(View view, int key, Object tag, boolean ignoreKey) {
        if (view != null) {
            if (ignoreKey || (key >>> 24) >= 2) {
                SparseArray<Object> tag2 = view.getTag();
                if (tag2 == null || !(tag2 instanceof SparseArray)) {
                    tag2 = new SparseArray();
                }
                SparseArray<Object> tagArray = tag2;
                tagArray.put(key, tag);
                view.setTag(tagArray);
                return;
            }
            throw new IllegalArgumentException("The key must be an application-specific resource id.");
        }
    }

    private static Object getTagInternal(View view, int key) {
        if (view == null) {
            return null;
        }
        SparseArray<Object> viewTag = view.getTag();
        if (viewTag == null || !(viewTag instanceof SparseArray)) {
            return null;
        }
        return viewTag.get(key);
    }

    public static void decorate(View hostView, View decorView, int gravity) {
        decorate(hostView, decorView, gravity, 0, 0, 0, 0);
    }

    public static void decorate(View hostView, View decorView, int gravity, int leftMargin, int topMargin, int rightMargin, int bottomMargin) {
        if (hostView != null && decorView != null) {
            ViewParent parent = hostView.getParent();
            if (parent != null && (parent instanceof ViewGroup) && decorView.getParent() == null) {
                FrameLayout decorContainer;
                LayoutParams hostLp = generateHostLayoutParams(hostView);
                LayoutParams decorLp = generateDecorLayoutParams(gravity, leftMargin, topMargin, rightMargin, bottomMargin);
                ViewGroup hostGroup = (ViewGroup) parent;
                if ((hostGroup instanceof FrameLayout) && getTag(hostView) == TAG_DECORATE) {
                    decorContainer = (FrameLayout) hostGroup;
                } else {
                    decorContainer = new DecorateContainer(hostGroup.getContext(), hostView);
                    int index = computeChildIndex(hostGroup, hostView);
                    ViewGroup.LayoutParams lp = hostView.getLayoutParams();
                    lp.width = -2;
                    lp.height = -2;
                    hostGroup.removeView(hostView);
                    hostGroup.addView(decorContainer, index, lp);
                    setTag(decorContainer, TAG_DECORATE);
                }
                decorContainer.removeAllViews();
                if (hostLp != null) {
                    decorContainer.addView(hostView, hostLp);
                }
                if (decorLp != null) {
                    decorContainer.addView(decorView, decorLp);
                }
            }
        }
    }

    private static LayoutParams generateHostLayoutParams(View hostView) {
        if (hostView == null) {
            return null;
        }
        LayoutParams lp = newLayoutParams(hostView.getLayoutParams());
        lp.bottomMargin = 0;
        lp.topMargin = 0;
        lp.rightMargin = 0;
        lp.leftMargin = 0;
        return lp;
    }

    private static LayoutParams generateDecorLayoutParams(int gravity, int leftMargin, int topMargin, int rightMargin, int bottomMargin) {
        LayoutParams lp = new LayoutParams(-2, -2);
        lp.gravity = gravity;
        lp.leftMargin = leftMargin;
        lp.topMargin = topMargin;
        lp.rightMargin = rightMargin;
        lp.bottomMargin = bottomMargin;
        return lp;
    }

    private static LayoutParams newLayoutParams(ViewGroup.LayoutParams source) {
        if (source == null) {
            return null;
        }
        if (source instanceof MarginLayoutParams) {
            return new LayoutParams((MarginLayoutParams) source);
        }
        return new LayoutParams(source);
    }

    private static int computeChildIndex(ViewGroup parent, View child) {
        if (parent == null || child == null) {
            return -1;
        }
        int index = 0;
        int count = parent.getChildCount();
        while (index < count && parent.getChildAt(index) != child) {
            index++;
        }
        if (index < 0 || index >= count) {
            return -1;
        }
        return index;
    }

    public static Bitmap capture(View view) {
        view.buildDrawingCache();
        Bitmap drawingCache = view.getDrawingCache();
        if (drawingCache == null) {
            return null;
        }
        WindowManager wm = (WindowManager) view.getContext().getSystemService("window");
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        Bitmap bitmap = Bitmap.createBitmap(drawingCache, 0, 0, Math.min(outMetrics.widthPixels, drawingCache.getWidth()), Math.min(outMetrics.heightPixels, drawingCache.getHeight()));
        if (view.isDrawingCacheEnabled()) {
            return bitmap;
        }
        view.destroyDrawingCache();
        return bitmap;
    }

    public static float getSpValue(float value) {
        return TypedValue.applyDimension(2, value, Ext.getContext().getResources().getDisplayMetrics());
    }

    public static boolean isChildOf(View c, View p) {
        if (c == p) {
            return true;
        }
        if (p instanceof ViewGroup) {
            int count = ((ViewGroup) p).getChildCount();
            for (int i = 0; i < count; i++) {
                if (isChildOf(c, ((ViewGroup) p).getChildAt(i))) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void getChildPos(View child, View parent, int[] posContainer) {
        if (posContainer != null && posContainer.length >= 2) {
            int x = 0;
            int y = 0;
            View vc = child;
            while (vc.getParent() != null) {
                x += vc.getLeft();
                y += vc.getTop();
                if (vc.getParent() == parent) {
                    posContainer[0] = x;
                    posContainer[1] = y;
                    if (posContainer.length >= 4) {
                        posContainer[2] = vc.getMeasuredWidth();
                        posContainer[3] = vc.getMeasuredHeight();
                    }
                    if (parent == null) {
                        posContainer[0] = x;
                        posContainer[1] = y;
                    }
                }
                try {
                    vc = (View) vc.getParent();
                    if (posContainer.length >= 4) {
                        posContainer[2] = vc.getMeasuredWidth();
                        posContainer[3] = vc.getMeasuredHeight();
                    }
                } catch (ClassCastException e) {
                }
            }
            if (parent == null) {
                posContainer[0] = x;
                posContainer[1] = y;
            }
        }
    }

    public static String getActivityName(Context ctx) {
        Context c = ctx;
        if (!(ctx instanceof Activity) && (ctx instanceof ContextWrapper)) {
            c = ((ContextWrapper) ctx).getBaseContext();
        }
        return c.getClass().getName();
    }

    public static int getStatusBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", ResourceUtils.dimen, "android");
        if (resourceId > 0) {
            return resources.getDimensionPixelSize(resourceId);
        }
        return 0;
    }

    public static float getDensity() {
        return density;
    }

    public static int getScreenWidth() {
        return screenWidth;
    }

    public static int getScreenHeight() {
        return screenHeight;
    }

    public static int dpToPx(float dp) {
        return Math.round(getDensity() * dp);
    }

    public static int pxToDp(float px) {
        return Math.round(px / getDensity());
    }

    public static int spToPx(float sp) {
        return (int) ((sp * Ext.getContext().getResources().getDisplayMetrics().scaledDensity) + 0.5f);
    }

    public static int pxTosp(float px) {
        return (int) ((px / Ext.getContext().getResources().getDisplayMetrics().scaledDensity) + 0.5f);
    }

    public static void setAlpha(View view, float alphaValue) {
        if (view != null) {
            if (VERSION.SDK_INT >= 11) {
                view.setAlpha(alphaValue);
                return;
            }
            AlphaAnimation alpha = new AlphaAnimation(alphaValue, alphaValue);
            alpha.setDuration(0);
            alpha.setFillAfter(true);
            view.startAnimation(alpha);
        }
    }

    public static void setViewBackground(View v, Drawable drawable) {
        if (v != null) {
            if (VERSION.SDK_INT < 16) {
                v.setBackgroundDrawable(drawable);
            } else {
                v.setBackground(drawable);
            }
        }
    }
}
